package quq.missq.utils;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.util.Base64;
import android.util.Log;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.StreamCorruptedException;

import quq.missq.beans.UserBean;

public class UserTools {

    public static UserBean.User getUser(Context context) {
        UserBean.User user = null;
        SharedPreferences preferences = context.getSharedPreferences("base64", Activity.MODE_PRIVATE);
        String productBase64 = preferences.getString("user", "utf-8");

        //读取字节
        byte[] base64 = Base64.decode(productBase64.getBytes(), Base64.DEFAULT);
        if (base64.length <= 10) {
            return null;
        }

        //封装到字节流
        ByteArrayInputStream bais = new ByteArrayInputStream(base64);
        try {
            //再次封装
            ObjectInputStream bis = new ObjectInputStream(bais);
            try {
                //读取对象
                user = (UserBean.User) bis.readObject();
            } catch (ClassNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        } catch (StreamCorruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return user;


    }

    public static void saveUser(Context context, UserBean.User user) {
        SharedPreferences preferences = context.getSharedPreferences("base64",
                Activity.MODE_PRIVATE);
        // 创建字节输出流

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            // 创建对象输出流，并封装字节流
            ObjectOutputStream oos = new ObjectOutputStream(baos);
            // 将对象写入字节流
            oos.writeObject(user);
            // 将字节流编码成base64的字符窜
            String oAuth_Base64 = new String(Base64.encode(baos
                    .toByteArray(), Base64.DEFAULT));
            SharedPreferences.Editor editor = preferences.edit();
            editor.putString("user", oAuth_Base64);

            editor.commit();
        } catch (IOException e) {
            e.printStackTrace();
            // TODO Auto-generated
        }
        Log.i("ok", "存储成功");

    }

    public static void logOut(Context context) {
        saveUser(context, null);
    }


}
